from Models import *

class GlobalVar:
    """
    全局变量单例类
    用于存储和管理全局变量
    """
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(GlobalVar, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self._variables = {}
            # 添加logger成员变量
            self.logger = logging.getLogger("App_Gloabl")
            self.logger.setLevel(logging.DEBUG)
            
            # 添加控制台处理器，使日志能够打印到控制台
            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            console_handler.setFormatter(formatter)
            self.logger.addHandler(console_handler)
            logfile = pathlib.Path("logs").mkdir(parents=True, exist_ok=True)
            logfile_handle = logging.FileHandler('logs/app.log')
            logfile_handle.setLevel(logging.DEBUG)
            logfile_handle.setFormatter(formatter)
            self.logger.addHandler(logfile_handle)
            
            GlobalVar._initialized = True
            
            
    
    def set_var(self, key, value):
        """设置全局变量"""
        self._variables[key] = value
        self.logger.debug(f"Set variable: {key} = {value}")
    
    def get_var(self, key, default=None):
        """获取全局变量"""
        value = self._variables.get(key, default)
        self.logger.debug(f"Get variable: {key} = {value}")
        return value
    
    def has_var(self, key):
        """检查是否存在指定的全局变量"""
        exists = key in self._variables
        self.logger.debug(f"Check variable existence: {key} = {exists}")
        return exists
    
    def delete_var(self, key):
        """删除全局变量"""
        if key in self._variables:
            del self._variables[key]
            self.logger.debug(f"Deleted variable: {key}")
    
    def clear_all(self):
        """清空所有全局变量"""
        count = len(self._variables)
        self._variables.clear()
        self.logger.info(f"Cleared all variables, count: {count}")
    
    def get_all_vars(self):
        """获取所有全局变量"""
        vars_copy = self._variables.copy()
        self.logger.debug(f"Retrieved all variables, count: {len(vars_copy)}")
        return vars_copy
    
    def print_all_vars(self):
        """打印所有全局变量"""
        print("="*50)
        print(f"正在打印所有全局变量，共 {len(self._variables)} 个变量")
        for index,(key, value) in enumerate(self._variables.items()):
            print(f"{index} \t {key} : {value}")
        print("="*50)




# 创建全局变量实例
# global_var = GlobalVar()
# global_var.set_var('test', 'hello world')
# print(global_var.get_all_vars())
# global_var.print_all_vars()